<!-- 页面 -->
<template>
	<s-layout navbar="custom">
		<view class="ss-flex video-player">
			<view class="video-wrapper">
				<view class="video-top">
					<view class="return-text" @tap="onClickLeft">返回</view>
					<view class="video-title">{{ state.current.lesson_name }}</view>
				</view>
				<view id="videoContain"></view>
			</view>
			<view class="right-sidebar" :style="{'visibility': loaded ? 'visible' : 'hidden'}">
				<view class="goods-title" v-if="loaded">
					<view>{{ state.goodsinfo.title }}</view>
					<view class="teacher-name">
						<view>主讲人: {{ state.goodsinfo.luboinfo.teacher_name || '计划社名师' }}</view>
						<view class="ss-flex-1"></view>
						<view>共{{state.goodsinfo.lessonNum}}节</view>
					</view>
				</view>
				<view class="mulu-list">
					<view class="tabs-container">
						<s-tabs class="sticky-tabs" :list="[{name:'目录', value: 0}, {name:'资料', value: 1}]" v-model="state.currentTab"/>
						<view class="tabs-content">
							<template v-if="state.currentTab === 0">
								<view class="mulu" v-for="(mulu, index) in state.mululist" :key="index"
									:ref="(el) => { if(parseInt(state.recordId) === mulu.id) activeItem = el?.[0] || el }"
									@click="navigateToCourse(mulu.id, mulu.is_audition)"
									:class="{'aa_active': parseInt(state.recordId) === mulu.id}">
									<view class="mulu-title">{{mulu.lesson_name}}</view>
									<view class="mulu-shiting">
										<view v-if="state.paid_auth || state.goodsinfo.luboinfo.luboisgkk=='1'">
											<span style="color:#99a1af;font-size: 20rpx;">已学{{mulu.LearnPercent}}%</span>
										</view>
										<view v-else>
											<uni-icons v-if="mulu.is_audition==1" custom-prefix="iconfont" type="icon-shiting" size="30"
												style="color:#99a1af;line-height: 1;"></uni-icons>
											<uni-icons v-if="mulu.is_audition==0" custom-prefix="iconfont" type="icon-suo" size="20"
												style="color:#99a1af"></uni-icons>
										</view>
									</view>
									
								</view>
							</template>
							<template v-else>
								<view class="mulu" v-for="(ziliao, index) in state.ziliaolist" :key="index">
									<view class="mulu_content">
										<view class="mulu-title">{{ziliao.lesson_name}}</view>
									</view>
									<view class="mulu-xiazai ss-flex">
										<view  @click="downloadZiliao(ziliao)">
											<span>下载</span>
										</view>
										<!-- <view @click="navigatorToZiliao(ziliao)">
											<span>查看</span>
										</view> -->
									</view>
								</view>
							</template>
						</view>
					</view>
				</view>
			</view>
		</view>
		
		<su-popup :show="state.isBuyVisible" type="center" round="10" :isMaskClick="false">
			<view class="model-box ss-flex-col">
				<view class="ss-m-t-56 ss-flex-col">
					<view class="score-title">您好！</view>
					<view class="model-title ss-flex ss-col-center ss-m-t-22 ss-m-b-30">
						本课为付费内容，请购买或兑换后学习!
					</view>
				</view>
				<view class="model-bg ss-flex-col ss-col-center ss-row-right">
					<view class="ss-m-b-40">
						<button class="ss-reset-button confirm-btn" @tap="onAddCart">{{state.goods_price}}购买本课程</button>
					</view>
				</view>
				<view class="btnclose" @click="handleClose">
					<uni-icons type="close" size="30"></uni-icons>
				</view>
			</view>
		</su-popup>
	</s-layout>
</template>

<script setup>
	import {
		computed,
		reactive
	} from 'vue';
	import {
		onLoad,
		onReady,
		onUnload,
		onHide
	} from '@dcloudio/uni-app';
	import sheep from '@/sheep';
	import _ from 'lodash';
	import {
		isEmpty
	} from 'lodash';
	import TCPlayer from 'tcplayer.js';
	import 'tcplayer.js/dist/tcplayer.min.css';
	import throttle from '@/sheep/helper/throttle.js';
	import {
		downloadFile
	} from '@/sheep/helper/download.js';

	const tradeManaged = computed(() => sheep.$store('app').has_wechat_trade_managed);
	 const hasHistory = sheep.$router.hasHistory();

	// 数据
	const state = reactive({
		currentTab: 0,
		error: 0,
		goodsId: '',
		recordId: 0,
		paid_auth: false, //后台计算的是否购买 
		goodsinfo: [],
		mululist: [],
		ziliaolist: [],
		player: null,
		currentindex: 0,
		current: []
	});

	const loaded = computed(() => {
		return !!state.current;
	});

	const tabMaps = [{
			name: '课程目录',
			value: 'jiangyi',
		}, {
			name: '资料讲义',
			value: 'ppt',
		}
	];

	// 添加ref用于存储当前激活的目录项元素
	let activeItem = null;

	const onResize = () => {
		throttle(() => {
			location.reload();
		}, 1000);
	}

	onLoad(async (options) => {
		state.goodsId = options.id
		state.recordId = options.recordId ? options.recordId : 0

		// const videos = document.querySelectorAll('video');
		// videos.forEach(video => {
		//   // 停止播放（如果正在播放）
		//   video.pause();

		//   // 移除元素（这将从DOM中完全删   除它）
		//   video.remove();
		// });

		getCourse(options.id, options.recordId);
		
		//监听页面直接关闭事件
		window.addEventListener(
			"beforeunload",
			beforeunloadHandler
		);

		window.addEventListener('resize', onResize);
	});

	onReady(async (options) => {

	});

	//页面在h5中跳转
	onUnload(async (options) => {
		savelearnrecord();
		window.removeEventListener('resize', onResize);
    state.player.dispose(); //销毁 ；
	});
	
	onHide(async (options) => {
		savelearnrecord();
	});
	
	// 切换选项卡
	function onTabsChange(e) {
		if (state.currentTab === e.index) return;
		state.currentTab = e.index;
	}

	function initVideo(res, current) {
		uni.getSystemInfo({
			success: resw => {
				// 根据宽度和16:9的比例计算高度  
				const el = document.getElementById('videoContain');
				var width = el.offsetWidth;
				// var height = (width / aspectRatio);
				var height = el.offsetHeight;

				const video = document.createElement("video")
				video.setAttribute("id", "player-container-id")
				// 设置样式以全屏显示视频，并保持宽高比  width: 100vh; height: 100vw;
				//video.style.cssText = 'position: absolute; top: 0; left: 0;  object-fit: cover;';  
				// 禁用浏览器默认的视频控制器  
				//video.controls = false;  

				// 在iOS微信浏览器中支持小窗内播放，并避免全屏播放（但我们希望全屏，所以这里可以忽略或移除这些属性）  
				video.setAttribute('playsinline', true);
				video.setAttribute('webkit-playsinline', true);
				video.setAttribute("width", width);
				video.setAttribute("height", height);

				video.setAttribute('autoplay', true)
				video.setAttribute("preload", "auto");

				// 在安卓中声明启用同层H5播放器（但这里我们更关心全屏播放，所以属性可以保留或根据需求调整）
				video.setAttribute("x5-video-player-type", "h5");
				video.setAttribute("x5-video-player-fullscreen", true);
				video.setAttribute("show-center-play-btn", false);
				video.setAttribute('x5-video-orientation', 'landscape'); // 设置横屏播放

				// let width = res.windowWidth;
				// let height = res.windowHeight;
				// video.setAttribute("height", res.windowWidth);
				// video.setAttribute("width", height);

				document.getElementById("videoContain").appendChild(video);

				initTcplayer(res, current);

			}
		})
	}


	function initTcplayer(res, current) {
		//console.log(TCPlayer('player-container-id').options_);
		// if(TCPlayer('player-container-id')){
		// 	TCPlayer('player-container-id').options_={}; 
		// }

		state.player = TCPlayer('player-container-id', { // player-container-id 为播放器容器 ID，必须与 html 中一致
			fileID: current.TencentFileId, // 请传入需要播放的视频 fileID（必须）
			appID: res.data.tecentinfo.appID, // 请传入点播账号的 appID（必须）
			//私有加密播放需填写 psign， psign 即播放器签名，签名介绍和生成方式参见链接：https://cloud.tencent.com/document/product/266/42436
			//psign:'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJhcHBJZCI6MTUwMDAwNTY5NiwiZmlsZUlkIjoiMzcwMTkyNTkyMTI5OTYzNzAxMCIsImN1cnJlbnRUaW1lU3RhbXAiOjE2MjY4NjAxNzYsImV4cGlyZVRpbWVTdGFtcCI6MjYyNjg1OTE3OSwicGNmZyI6InByaXZhdGUiLCJ1cmxBY2Nlc3NJbmZvIjp7InQiOiI5YzkyYjBhYiJ9LCJkcm1MaWNlbnNlSW5mbyI6eyJleHBpcmVUaW1lU3RhbXAiOjI2MjY4NTkxNzksInN0cmljdE1vZGUiOjJ9fQ.Bo5K5ThInc4n8AlzIZQ-CP9a49M2mEr9-zQLH9ocQgI',
			licenseUrl: res.data.tecentinfo.licenseUrl, // 参考准备工作部分，在视立方控制台申请 license 后可获得 licenseUrl
			//muted: true, // 设置为静音 
			controlBar: {
				progressControl: true,
				QualitySwitcherMenuButton: false
			}
		});
		//从哪个时间开始播放seconds
		state.player.currentTime(current.LearnSecond);
	}

	//跳转别的小节
	function navigateToCourse(id, is_audition) {
		if (state.paid_auth || is_audition == 1) {
			sheep.$router.go('/pages/course/lubo', {
				id: state.goodsId,
				recordId: id
			})
			savelearnrecord();
		} else {
			state.isBuyVisible = true
		}
		state.player.dispose(); //销毁 ；
	};


	function getCourse(goodsId, recordId) {
		sheep.$api.course.lubo({
			'goods_id': state.goodsId,
			'recordId': recordId
		}).then((res) => {
			if (res.code === 1) {
				state.paid_auth = res.data.result.paid_auth;
				state.goodsinfo = res.data.result.goodsinfo;
				state.mululist = res.data.result.recordlist;
				state.ziliaolist = res.data.result.ziliaolist;
				
				var isshiting = -1;
				for(var i=0; i<res.data.result.recordlist.length; i++){
					if(res.data.result.recordlist[i].is_audition==1){
						isshiting = i;
						break;
					}
				}
				if((isshiting>-1||state.paid_auth||state.goodsinfo.luboinfo.luboisgkk=='1') && res.data.result.recordlist.length>0){
					state.currentindex = res.data.result.recordlist.findIndex(lesson => lesson.id === parseInt(res.data.result.current));
					if(state.currentindex==0){
						state.currentindex == isshiting;
					}
					var current = res.data.result.recordlist[state.currentindex];
					state.current = current;
					console.log(current)
					state.recordId = res.data.result.current; 
			
					uni.setNavigationBarTitle({
						title: current.lesson_name
					});
					initVideo(res, current);
					// 等待DOM更新后滚动到当前项
					setTimeout(() => {
						if (activeItem && activeItem.$el) {
							activeItem.$el.scrollIntoView({ 
								behavior: 'smooth',
								block: 'center'
							});
						}
					}, 100);
				}else {
					if(!state.paid_auth){
						state.isBuyVisible = true
					}
				}
			}
		})
	};
	
	
	// 添加购物车
	function onAddCart() {
		sheep.$api.goods.detail(state.goodsId).then((res) => {
			console.log(res);
			if (res.code === 1) {
				sheep.$api.cart.append({
					'goods_id': res.data.sku_prices[0].goods_id,
					'goods_sku_price_id': res.data.sku_prices[0].id,
					'type': "inc"
				}).then((res) => {
					console.log(res)
					if (res.code === 1) {
						state.isBuyVisible = false;
						sheep.$router.go('/pages/index/cart', {})
					} else {
						console.log("加入购物车失败！");
					}
				});
			} else {
				// 未找到商品
				console.log("未找到")
			}
		});
	}
	
	//保存用户学习记录
	function savelearnrecord() {
		console.log(state.player.currentTime())
		sheep.$api.course.saveLearRrecord({
			'goods_id': state.goodsId,
			'lesson_id': state.recordId,
			'LearnSecond': state.player.currentTime(),
			'source': 'h5',
			'url': 'aaaaaa'
		}).then((res) => {
			console.log(res);
			if (res.code === 1) {
				console.log("存储学习记录成功")
			} else {
				// 未找到商品
				console.log("未找到")
			}
		});
	};
	
	function beforeunloadHandler(e) {
		// 兼容性处理，确保在所有浏览器中都能正确设置returnValue
		const event = e || window.event;
	
		savelearnrecord();
	
		// 设置returnValue属性，这将触发浏览器的默认离开确认对话框  
		// 注意：现代浏览器可能会忽略自定义文本，只显示默认的对话框  
		event.returnValue = '您确定要离开这个页面吗？'; // 老版本浏览器  
	
		// 对于现代浏览器，除了设置returnValue，还需要返回一个字符串  
		// 但请注意，这个字符串可能不会在所有浏览器中作为对话框文本显示  
		return '您确定要离开这个页面吗？'; // 现代浏览器  
	};
	
	function navigatorToZiliao(lesson) {
		if (state.paid_auth || lesson.is_audition == 1) {
			sheep.$router.navigatorToZiliao(lesson.id, 'lesson');
		} else {
			state.isBuyVisible = true
		}
	}

	function downloadZiliao(lesson) {
		if (state.paid_auth || is_audition == 1) {
			downloadFile(lesson.download_url, lesson.lesson_name);
		} else {
			state.isBuyVisible = true
		}
	}
	
	function onClickLeft() {
	    if (hasHistory) {
	        sheep.$router.back();
	    } else {
	        sheep.$router.go('/pages/index/index');
	    }
	}
	
	function durationInMinutes(Duration) {
	      // 使用 Math.floor() 向下取整
	      // 如果你想要四舍五入，可以使用 Math.round()
	      // 如果你想要向上取整，可以使用 Math.ceil()
	      return Math.floor(Duration / 60);
	    }
</script>

<style lang="scss" scoped>
	@import "@/static/iconfont/iconfont.css";
	.video-top{
		display:flex;
		height: 60px;
		line-height: 60px;
		background-color: #1a1a1a;
		flex-shrink: 0;
	}
	.return-text{
		font-size: 14px;
		color: #cccccc;
		border-right: 1px solid #cccccc;
		padding: 0px 15px;
		cursor:pointer;
	}
	#player-container-id {
	      width: 100%;
	      max-width: 100%;
	      height: 0;
	      padding-top: 56.25%;
	    }

	.courseinfo {
		font-size: 28rpx;
		padding: 13px;
		width: 100%;
		min-height: 100px;
		background: #FFFFFF;
		box-sizing: border-box;
	}

	.mulu_content {
		width: 90%;
	}

	.mulu-title {
		font-size: 14px;
		flex-grow: 1;
	}

	.mulu-xiazai {
		flex-shrink: 0;
		cursor: pointer;
		color:#9fa3a2;
		& > * {
			margin-left: 5px;
		}
	}

	.mulu_icon {
		width: 50px;
		text-align: center;
		margin-top: 10px;
	}

	.mulu {
		display: flex;
		align-items: flex-start;
		margin-bottom: 5px;
	}

	.mulu-shiting {
		flex-shrink: 0;
		font-size: 14px;
	}

	.aa_active {
		color: #da6e04 !important;
	}

	.aa_active .uni-icons {
		color: #c66200 !important;

	}

	.mulu-time {
		font-size: 12px;
		color: #999999;
		background-size: 14px;
		height: 20px;
		line-height: 24px;
		margin-top: 10px;
		border: none;
	}
	
	.model-box {
		width: 520rpx;
		border-radius: 10rpx;
		padding: 5px 20px;
		position: relative;
	
		.cicon-check-round {
			font-size: 70rpx;
			color: #fff;
		}
	
		.score-title {
			font-size: 34rpx;
			font-family: OPPOSANS;
			font-weight: 500;
			color: #000000;
		}
	
		.model-title {
			font-size: 34rpx;
			font-weight: 500;
			color: #000000;
		}
	
		.model-bg {
			width: 520rpx;
			height: 144rpx;
			background-size: 100% 100%;
			background-image: v-bind(headerBg);
			background-repeat: no-repeat;
			border-radius: 0 0 10rpx 10rpx;
	
			.title {
				font-size: 34rpx;
				font-weight: bold;
				// color: var(--ui-BG-Main);
				color: #ff6000;
			}
	
			.subtitle {
				font-size: 26rpx;
				font-weight: 500;
				color: #999999;
			}
	
			.cancel-btn {
				width: 220rpx;
				height: 70rpx;
				border: 2rpx solid #ff6000;
				border-radius: 35rpx;
				font-size: 28rpx;
				font-weight: 500;
				color: #ff6000;
				line-height: normal;
				margin-right: 10rpx;
			}
	
			.confirm-btn {
				width: 320rpx;
				height: 70rpx;
				background: linear-gradient(90deg, #ff6000, #fe832a);
				box-shadow: 0 0.2em 0.5em rgba(#ff6000, 0.4);
				border-radius: 35rpx;
				font-size: 28rpx;
				font-weight: 500;
				color: #ffffff;
				line-height: normal;
			}
		}
	
		.btnclose {
			position: absolute;
			right: 10px;
			top: 10px;
			width: 30px;
			height: 31px;
		}
	}

	.video-player {
		height: 100vh;
		width: 100vw;
	}
	.video-wrapper {
		position: relative;
		display: flex;
		flex-direction: column;
		height: 100%;
		flex-grow: 1;

		.video-title {
			padding-left: 20px;
			height: 60px;
			line-height: 60px;
			background-color: #1a1a1a;
			flex-shrink: 0;
			color: white;
			font-size: 20px;
		}

		#videoContain {
			height: calc(100% - 60px);
		}
	}
	.right-sidebar {
		display: flex;
		flex-direction: column;
		width: 300px;
		flex-shrink: 0;
		height: 100%;
		border-left: 6px solid #3E3E3E;
	}

	.goods-title {
		font-size: 16px;
		font-weight: bold;
		background-color: #0C1A29;
		color: white;
		padding: 10px;
		flex-shrink: 0;
	}
	.teacher-name {
		display: flex;
		margin-top: 10px;
		font-size: 14px;
		color: #ccc;
	}

	.mulu-list {
		flex-grow: 1;
		overflow: auto;
		padding: 0 10px;
	}
	.sticky-tabs {
		position: sticky;
		top: 0;
		z-index: 100;
		margin-bottom: 10px;
		background-color: #fff;
	}
</style>
